import React, { useState } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import CaptchaImage from '../../src/components/CaptchaImage';

type RootStackParamList = {
  Zhuce: undefined;
  Denglu: undefined;
  Daohang: undefined;
};

type NavigationProp = NativeStackNavigationProp<RootStackParamList, 'Zhuce'>;

const RegisterScreen = () => {
  const navigation = useNavigation<NavigationProp>();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [qq, setQQ] = useState('');
  const [phone, setPhone] = useState('');
  const [captcha, setCaptcha] = useState('');
  const [inputCaptcha, setInputCaptcha] = useState('');
  const [isFormValid, setIsFormValid] = useState(false);
  const [usernameError, setUsernameError] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [confirmPasswordError, setConfirmPasswordError] = useState('');
  const [qqError, setQQError] = useState('');
  const [phoneError, setPhoneError] = useState('');
  const [captchaError, setCaptchaError] = useState('');

  const validateForm = () => {
    const isUsernameValid = username.length >= 3;
    const isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/.test(password);
    const isConfirmPasswordValid = password === confirmPassword;
    const isPhoneValid = /^1[3-9]\d{9}$/.test(phone);
    const isCaptchaValid = inputCaptcha.toUpperCase() === captcha;
    
    setUsernameError(isUsernameValid ? '' : '用户名至少3个字符');
    setPasswordError(isPasswordValid ? '' : '密码必须包含大小写字母和数字，且长度至少6位');
    setConfirmPasswordError(isConfirmPasswordValid ? '' : '两次输入的密码不一致');
    setPhoneError(isPhoneValid ? '' : '请输入正确的手机号');
    setCaptchaError(isCaptchaValid ? '' : '验证码错误');
    
    setIsFormValid(isUsernameValid && isPasswordValid && isConfirmPasswordValid && isPhoneValid && isCaptchaValid);
  };

  const handleCaptchaChange = (newCaptcha: string) => {
    setCaptcha(newCaptcha);
    // 立即用新验证码校验
    const isUsernameValid = username.length >= 3;
    const isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/.test(password);
    const isConfirmPasswordValid = password === confirmPassword;
    const isPhoneValid = /^1[3-9]\d{9}$/.test(phone);
    const isCaptchaValid = inputCaptcha.toUpperCase() === newCaptcha;
    
    setUsernameError(isUsernameValid ? '' : '用户名至少3个字符');
    setPasswordError(isPasswordValid ? '' : '密码必须包含大小写字母和数字，且长度至少6位');
    setConfirmPasswordError(isConfirmPasswordValid ? '' : '两次输入的密码不一致');
    setPhoneError(isPhoneValid ? '' : '请输入正确的手机号');
    setCaptchaError(isCaptchaValid ? '' : '验证码错误');
    
    setIsFormValid(isUsernameValid && isPasswordValid && isConfirmPasswordValid && isPhoneValid && isCaptchaValid);
  };

  const handleRegister = async () => {
    if (isFormValid) {
      try {
        const response = await fetch('http://192.168.78.1:3000/users/register', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username,
            password,
            phone,
            youxiang: qq // 使用qq字段作为邮箱
          })
        });

        const data = await response.json();
        
        if (response.ok) {
          // 注册成功
          Alert.alert('成功', '注册成功！');
          navigation.navigate('Denglu');
        } else {
          // 显示错误信息
          Alert.alert('错误', data.message || '注册失败，请重试');
        }
      } catch (error) {
        console.error('注册请求失败:', error);
        Alert.alert('错误', '网络错误，请检查网络连接后重试');
      }
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity style={styles.backBtn} onPress={() => navigation.goBack()}>
          <Text style={styles.backBtnText}>{'<'}</Text>
        </TouchableOpacity>
        <Text style={styles.headerTitle}>注册</Text>
      </View>
      <View style={styles.form}>
        {usernameError ? <Text style={styles.errorText}>{usernameError}</Text> : null}
        <TextInput 
          style={[styles.input, usernameError ? styles.inputError : null]} 
          placeholder="输入账号" 
          placeholderTextColor="#bbb"
          value={username}
          onChangeText={setUsername}
          onBlur={validateForm}
        />
        {passwordError ? <Text style={styles.errorText}>{passwordError}</Text> : null}
        <TextInput 
          style={[styles.input, passwordError ? styles.inputError : null]} 
          placeholder="输入密码" 
          placeholderTextColor="#bbb" 
          secureTextEntry
          value={password}
          onChangeText={setPassword}
          onBlur={validateForm}
        />
        {confirmPasswordError ? <Text style={styles.errorText}>{confirmPasswordError}</Text> : null}
        <TextInput 
          style={[styles.input, confirmPasswordError ? styles.inputError : null]} 
          placeholder="确认密码" 
          placeholderTextColor="#bbb" 
          secureTextEntry
          value={confirmPassword}
          onChangeText={setConfirmPassword}
          onBlur={validateForm}
        />
        {qqError ? <Text style={styles.errorText}>{qqError}</Text> : null}
        <TextInput 
          style={[styles.input, qqError ? styles.inputError : null]} 
          placeholder="QQ" 
          placeholderTextColor="#bbb"
          value={qq}
          onChangeText={setQQ}
          keyboardType="numeric"
          onBlur={validateForm}
        />
        {phoneError ? <Text style={styles.errorText}>{phoneError}</Text> : null}
        <TextInput 
          style={[styles.input, phoneError ? styles.inputError : null]} 
          placeholder="手机号" 
          placeholderTextColor="#bbb" 
          keyboardType="phone-pad"
          value={phone}
          onChangeText={setPhone}
          onBlur={validateForm}
        />
        <View style={styles.captchaContainer}>
          <TextInput 
            style={[styles.input, styles.captchaInput, captchaError ? styles.inputError : null]} 
            placeholder="输入验证码" 
            placeholderTextColor="#bbb"
            value={inputCaptcha}
            onChangeText={setInputCaptcha}
            onBlur={validateForm}
          />
          <CaptchaImage onCaptchaChange={handleCaptchaChange} />
        </View>
        {captchaError ? <Text style={styles.errorText}>{captchaError}</Text> : null}
        <TouchableOpacity 
          style={[styles.registerBtn, !isFormValid && styles.registerBtnDisabled]} 
          onPress={handleRegister}
          disabled={!isFormValid}
        >
          <Text style={[styles.registerBtnText, !isFormValid && styles.registerBtnTextDisabled]}>注册</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
    marginBottom: 10,
    position: 'relative',
  },
  backBtn: {
    position: 'absolute',
    left: 10,
    top: 0,
    height: 50,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 10,
    zIndex: 1,
  },
  backBtnText: {
    fontSize: 22,
    color: '#333',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
  },
  form: {
    paddingHorizontal: 20,
    flex: 1,
    top: 50,
  },
  input: {
    height: 40,
    backgroundColor: '#f5f5f5',
    borderRadius: 5,
    paddingHorizontal: 10,
    marginBottom: 15,
    fontSize: 14,
  },
  inputError: {
    borderColor: '#d32f2f',
    borderWidth: 1,
  },
  captchaContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 15,
  },
  captchaInput: {
    flex: 1,
    marginRight: 10,
    marginBottom: 0,
  },
  registerBtn: {
    backgroundColor: '#d32f2f',
    borderRadius: 5,
    height: 45,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 10,
  },
  registerBtnDisabled: {
    backgroundColor: '#cccccc',
  },
  registerBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  registerBtnTextDisabled: {
    color: '#666666',
  },
  errorText: {
    color: 'red',
    fontSize: 12,
    marginBottom: 5,
    marginLeft: 5,
  },
});

export default RegisterScreen;